package com.lznb.cloud.config;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

public class ThreePasswordEncoder {
    private static String Algorithm = "DES";

    public  static String encode(String s) {

        return encrypt(s, "20010101");
    }

    public static String encrypt(String src, String key) {
        String str = null;

        byte[] arr = src.getBytes();
        if ((key.length() == 8) || (key.length() == 24)) {
            if (key.length() == 8) {
                Algorithm = "DES";
                byte[] keybyte = new byte[8];
                keybyte = key.getBytes();
                str = byte2hex(encryptMode(arr, keybyte));
            } else {
                Algorithm = "DESede";
                byte[] keybyte = new byte[24];
                keybyte = key.getBytes();
                str = byte2hex(encryptMode(arr, keybyte));
            }
        }
        return str;
    }

    private static byte[] encryptMode(byte[] src, byte[] key) {
        SecureRandom sr = new SecureRandom();
        try {
            DESKeySpec dks = new DESKeySpec(key);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Algorithm);
            SecretKey securekey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(Algorithm);
            cipher.init(1, securekey, sr);
            return cipher.doFinal(src);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";

        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }
}
